package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Map search(Map<String, String> searchMap) throws Exception {
        //设置封装查询结果
        Map<String,Object> resultMap = new HashMap<String,Object>();

        //判断searchMap是否为空
        if (searchMap!=null){

            //组合条件对象
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            //  0:关键词
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))) {
                //拼接查询条件
                boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
            }

            //  1.条件 品牌
            if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
                boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
            }

            //2.条件 规格
            for (String key : searchMap.keySet()) {
                if (key.startsWith("spec_")){
                    String value = searchMap.get(key).replace("%2B","+");
                    //spec_网络制式
                    boolQuery.filter(QueryBuilders.termQuery("specMap."+key.substring(5)+".keyword",value));
                }
            }

            //3.条件 价格
            if (StringUtils.isNotEmpty(searchMap.get("price"))){
                String[] prices = searchMap.get("price").split("-");
                if (prices.length==2){
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }

            //4.原生搜索实现类  构建查询条件封装对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQuery);

            //6.品牌聚合查询
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //规格聚合(分组)查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            //分页
            String pageNum = searchMap.get("pageNum");
            String pageSize = searchMap.get("pageSize");
            if (pageNum==null){
                pageNum = "1";
            }
            if (pageSize==null){
                pageSize = "30";
            }
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1,Integer.parseInt(pageSize)));

            //按照相关字段进行排序查询
            //1.当前域 2当前的排序操作(升序ASC,降序DESC)
            if (StringUtils.isNotEmpty(searchMap.get("sortField"))&&StringUtils.isNotEmpty(searchMap.get("sortRule"))){
                if ("ASC".equals(searchMap.get("sortRule"))){
                    //升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.ASC));
                }else {
                    //降序
//                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                }
            }

            //设置高亮域以及高亮的样式
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")
                    .preTags("<span style='color:red'>")
                    .postTags("</span>");
            nativeSearchQueryBuilder.withHighlightFields(field);
            //10.执行查询,返回结果对象
                /*
                    第一个参数:条件构建对象
                    第二个参数:操作实体类
                    第三个参数:结果操作对象
                 */
            AggregatedPage<SkuInfo> aggregatedPage = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(),
                    SkuInfo.class, new SearchResultMapper() {
                        //查询结果操作,转换为SkuInfo
                        @Override
                        public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                            List<T> list = new ArrayList<>();
                            //获取查询的命中对象
                            SearchHits hits = searchResponse.getHits();
                            if (hits!=null) {
                                for (SearchHit hit : hits) {
                                    SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);
                                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                                    if (highlightFields!=null&&highlightFields.size()>0){
                                        skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                                    }
                                    list.add((T) skuInfo);
                                }
                            }
                            return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                        }
                    });
            //11.总条数
            resultMap.put("total", aggregatedPage.getTotalElements());
            //12.总页数
            resultMap.put("totalPages", aggregatedPage.getTotalPages());
            //13.查询结果集合
            resultMap.put("rows", aggregatedPage.getContent());

            //14.获取品牌聚合结果
            StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);

            //14.获取 规格聚合结果
            StringTerms specTerms= (StringTerms) aggregatedPage.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList",this.formatSpec(specList));
            //当前页
            resultMap.put("pageNum",pageNum);
            return resultMap;
            }
        return resultMap;
    }


    //转换规格显示
    public Map<String, Set<String>> formatSpec(List<String> specList){
        //封装返回结果
        Map<String, Set<String>> resultMap = new HashMap<>();
        //遍历规格集合
        if (specList!=null&&specList.size()>0){
            //获取集合总每一个规格字符串
            for (String specJson : specList) {
                //将每个字符串转化为Map
                Map<String,String> specMap = JSON.parseObject(specJson, Map.class);
                //遍历map,获取每一个键的值
                for (String specKey : specMap.keySet()) {
                    //通过键获取规格信息,装入set集合中
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet==null){
                        specSet=new HashSet<>();
                    }
                    //将规格信息存入set中
                    specSet.add(specMap.get(specKey));
                    resultMap.put(specKey,specSet);
                }
            }
        }
        return resultMap;
    }
}
